<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas Drag Example</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>

<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');

    // 矩形的初始位置和大小
    let rect = {
        x: 200,
        y: 200,
        width: 50,
        height: 50,
        isDragging: false
    };

    // 绘制矩形
    function drawRect() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = 'blue';
        ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
    }

    // 鼠标按下事件
    canvas.addEventListener('mousedown', (e) => {
        const rectX = rect.x;
        const rectY = rect.y;
        const rectWidth = rect.width;
        const rectHeight = rect.height;

        if (e.offsetX >= rectX && e.offsetX <= rectX + rectWidth &&
            e.offsetY >= rectY && e.offsetY <= rectY + rectHeight) {
            rect.isDragging = true;
            rect.dragOffsetX = e.offsetX - rectX;
            rect.dragOffsetY = e.offsetY - rectY;
        }
    });

    // 鼠标移动事件
    canvas.addEventListener('mousemove', (e) => {
        if (rect.isDragging) {
            rect.x = e.offsetX - rect.dragOffsetX;
            rect.y = e.offsetY - rect.dragOffsetY;
            drawRect();
        }
    });

    // 鼠标松开事件
    canvas.addEventListener('mouseup', () => {
        rect.isDragging = false;
    });

    drawRect();
</script>
</body>

</html>